package Chapter25.jdbc.batch_;

import Chapter25.jdbc.utils.JDBCUtils;
import org.junit.jupiter.api.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author 杨森
 * @date 2022年11月20日 22:08
 * 演示java的批处理
 */
public class Batch_ {
    //传统方法，添加5000条数据到admin2
    @Test
    public void noBath() throws SQLException {
        Connection connection= JDBCUtils.getConnection();
        String sql="insert into admin2 values (null,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        System.out.println("开始执行");
        long start =System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
            preparedStatement.setString(1, "jack"+i);
            preparedStatement.setString(2, "666");
            preparedStatement.executeUpdate();
        }
        long end = System.currentTimeMillis();
        System.out.println("传统的方式 耗时="+(end-start));
        JDBCUtils.close(null,preparedStatement,connection);

    }

    //使用批量处理方法
    @Test
    public void useBath() throws Exception {
        Connection connection= JDBCUtils.getConnection();
        String sql="insert into admin2 values (null,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        System.out.println("开始执行");
        long start =System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
            preparedStatement.setString(1, "jack"+i);
            preparedStatement.setString(2, "666");
            preparedStatement.addBatch();
            //当有1000条记录时，再批量执行
            if ((i+1)%1000==0){
                preparedStatement.executeBatch();
                preparedStatement.clearBatch();

            }
        }
        long end = System.currentTimeMillis();
        System.out.println("批量方式 耗时="+(end-start));
        JDBCUtils.close(null,preparedStatement,connection);

    }
}
